package com.kadron.datamodel;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.kadron.creator.KCommentModelCreator;
import com.kadron.dao.KCommentDAO;
import com.kadron.entity.Comment;

public class KCommentAdminDataProvider implements KDataProvider {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6519828535000988790L;
	
	private KCommentModelCreator creator;
	private KCommentDAO commentDAO;
	
	public KCommentAdminDataProvider(KCommentModelCreator creator,KCommentDAO commentDAO) {
		super();
		this.creator = creator;
		this.commentDAO = commentDAO;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Long> getItemsByRange(Integer integer, int numberOfRows,
			Object object, boolean b) {
		EntityManager em = commentDAO.getEntityManager();
		StringBuilder builder = new StringBuilder("SELECT e.id FROM Comment e WHERE e.id > 0 ");
		builder.append(" ORDER BY e.approved, e.id DESC");
		Query query = em.createQuery(builder.toString());
		return query.setFirstResult(integer).setMaxResults(numberOfRows).getResultList();
	}

	@Override
	public KModel getItemById(Long id, KModelCreator creator) {
		return creator.create(id);
	}

	@Override
	public int getRowCount() {
		EntityManager em = commentDAO.getEntityManager();
		StringBuilder builder = new StringBuilder("SELECT COUNT(e.id) FROM Comment e WHERE e.id > 0 ");
		Query query = em.createQuery(builder.toString());
		Long count = (Long) query.getSingleResult();
		return (count == null) ? 0 : count.intValue() ;
	}

	@Override
	public boolean hasItemWithId(Long id) {
		return commentDAO.exists(id, Comment.class);
	}

	@Override
	public KCommentModelCreator getCreator() {
		return creator;
	}

}
